package com.jtw.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.List;

/**
 * DESCRIPT:
 *
 * @author cjsky666
 * @date 2018/11/26 23:25
 */
@Slf4j
public class HttpUtil {
    /**
     * 根据url进行请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(8000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();
        HttpEntity entity = null;
        String res = null;
        try {
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            httpget.setConfig(requestConfig);
            log.info("当前请求的接口是 " + httpget.getURI());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                entity = response.getEntity();
                if (entity != null) {
                    res = EntityUtils.toString(entity, "utf-8");
                }
                return res;
            } finally {
                response.close();
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;

    }

    /**
     * 上传文件
     *
     * @param url
     * @param file
     * @param fileName
     * @param comment
     * @param stringBodyName
     * @return
     */
    public static String upload(String url, File file, String fileName, StringBody comment, String stringBodyName) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(30000)
                .setConnectionRequestTimeout(10000)
                .build();
        HttpEntity entity = null;
        String res = null;
        try {
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            httppost.setConfig(requestConfig);
            FileBody bin = new FileBody(file);
//            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(fileName, bin).addPart(stringBodyName, comment).build();
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                entity = response.getEntity();
                if (entity != null) {
                    log.error("返回的数据是: " + entity.getContentLength());
                    res = EntityUtils.toString(entity, "utf-8");
                }
                return res;
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, List<NameValuePair> nameValuePairList, String charsetFormet) {
        if (charsetFormet == null) {
            charsetFormet = "UTF-8";
        }
        RequestConfig requestConfig = RequestConfig
                .custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpEntity entity = null;
        String res = null;
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity urlEntity;
        try {
            urlEntity = new UrlEncodedFormEntity(nameValuePairList, charsetFormet);
            httppost.setEntity(urlEntity);
            httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            httppost.setConfig(requestConfig);
            log.info("当前请求的接口是" + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                entity = response.getEntity();
                if (entity != null) {
                    res = EntityUtils.toString(entity, "utf-8");
                    log.info("返回的数据是: {}", res);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                EntityUtils.consume(entity);
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * SSLGet连接
     */
    public static HttpEntity sslGet(String url, String password, KeyStore trustStore, File file) {
        CloseableHttpClient httpclient = null;
        RequestConfig requestConfig = RequestConfig
                .custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(30000)
                .setConnectionRequestTimeout(10000)
                .build();
        HttpEntity entity = null;
        try {
            FileInputStream instream = new FileInputStream(file);
            try {
                trustStore.load(instream, password.toCharArray());
            } catch (CertificateException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } finally {
                try {
                    instream.close();
                } catch (Exception ignore) {
                }
            }
            // 相信自己的CA和所有自签名的证书
            javax.net.ssl.SSLContext sslcontext = null;
            try {
                sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            }
            // 只允许使用TLSv1协议
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
                    NoopHostnameVerifier.INSTANCE);
            httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            httpget.setConfig(requestConfig);
            log.info("当前请求的接口URL" + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                entity = response.getEntity();
                log.info(response.getStatusLine().toString());
                if (entity != null) {
                    log.info("返回报文长度: " + entity.getContentLength());
                    log.info(EntityUtils.toString(entity));
                    EntityUtils.consume(entity);
                }
            } finally {
                httpclient.close();
                response.close();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }
}
